﻿using System;
using System.IO;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using KewlStuff.DataStructures;
using MovieBuddy.Controls;

namespace MovieBuddy.Helpers
{
    public class ImageCache
    {
        private static readonly LruCache<string, BitmapImage> SmallImages = new LruCache<string, BitmapImage>(1000);
        private static readonly LruCache<string, BitmapImage> LargeImages = new LruCache<string, BitmapImage>(30);

        public static BitmapImage GetImage(string location)
        {
            return GetImage(new Uri(location));
        }

        public static BitmapImage GetImage(Uri uri)
        {
            var image = SmallImages[uri.ToString()] ?? LargeImages[uri.ToString()];
            if (image == null)
            {
                image = new BitmapImage(uri);
                var cache = (image.PixelHeight * image.PixelWidth) > 10000 ? LargeImages : SmallImages;
                cache[uri.ToString()] = image;
            }
            return image;
        }

        public static ImageSource GetImage(FilePickerUpdatedEventArgs eventArgs)
        {
            if (eventArgs.IsNull()) return null;
            return GetImage(eventArgs.ItemUri);
        }
    }
}
